package com.yyt.yytcodesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.yyt.yytcodesandbox.model.ExecuteCodeRequest;
import com.yyt.yytcodesandbox.model.ExecuteCodeResponce;
import com.yyt.yytcodesandbox.model.ExecuteMessage;
import com.yyt.yytcodesandbox.model.JudgeInfo;
import com.yyt.yytcodesandbox.utils.ProcessUtils;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class JavaDockerCodeSandboxOld implements CodeSandbox{

    private static final String GLOBAL_CODE_DIR_NAME="tmpCode";
    private static final String GLOBAL_CODE_CLASS_NAME="Main.java";
    private static final Long TIME_LIMIT=10000L;
    private static final List<String> blackList=Arrays.asList("Files","exec");
    private static final String SECURITY_MANAGER_PATH="yyt-code-sandbox/src/main/resources/security";
    private static final String SECURITY_CLASS_NAME="DefaultSecurityManager";
    private static final Boolean FIRST_INIT=true;
    private static final WordTree WORD_TREE;
    static {
        WORD_TREE=new WordTree();
        WORD_TREE.addWords(blackList);
    }

    public static void main(String[] args) {
        JavaDockerCodeSandboxOld javaDockerCodeSandbox = new JavaDockerCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        String userDir = System.getProperty("user.dir");
        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);
        //String code=ResourceUtil.readStr("testCode/unsafe/SleepError",StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setInputList(Arrays.asList("1 2","2 5"));
        executeCodeRequest.setCodeLanguage("java");
        ExecuteCodeResponce executeCodeResponce = javaDockerCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponce);
    }

    @Override
    public ExecuteCodeResponce executeCode(ExecuteCodeRequest executeCodeRequest) {
        ExecuteCodeResponce executeCodeResponce=new ExecuteCodeResponce();
        //1、把用户的代码保存为文件
        String code= executeCodeRequest.getCode();
        //校验代码中是否含黑名单——可用java安全管理器替代
//        FoundWord foundWords = WORD_TREE.matchWord(code);
//        if(foundWords!=null){
//            executeCodeResponce.setMessage("包含禁止词"+foundWords.getFoundWord());
//            return executeCodeResponce;
//        }

        String userDir = System.getProperty("user.dir");
        String globalCodePathName=userDir+ File.separator+GLOBAL_CODE_DIR_NAME;
        if(!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }
        //每份代码独立存储
        String userCodeParentPath=globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath=userCodeParentPath+File.separator+GLOBAL_CODE_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2、编译代码，得到class文件，获得编译输出信息
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        System.out.println(compileCmd);
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            return getErrorResponce(e,userCodeFile);
        }

        //3、创建容器，把编译好的文件上传到容器环境内
        DockerClient dockerClient= DockerClientBuilder.getInstance().build();
        //初次拉取镜像
        String image = "openjdk:8-alpine";
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
            System.out.println("下载完成");
        }
        //在已有镜像的基础上再扩充：拉去现成的jdk，拥有java运行的环境,创建一个可交互的容器，能接受多次输入输出
        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig=new HostConfig();
        //挂载数据集，把编译好的文件传到docker中,可以在共享空间/app中去执行代码
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        hostConfig.withMemory(100*1000*1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        CreateContainerResponse createContainerResponse=createContainerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        String containerId = createContainerResponse.getId();
        System.out.println(createContainerResponse);

        //4、在docker中执行文件，得到输出结果
        dockerClient.startContainerCmd(containerId).exec();
        //执行命令 docker exec containerId java -cp /app Main input
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        List<String> inputList = executeCodeRequest.getInputList();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0L;
            // 判断是否超时
            final boolean[] timeout = {true};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成，则表示没超时
                    System.out.println("没超时");
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    System.out.println("这是结果:"+streamType+"  "+frame.getPayload());
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};

            // 获取占用的内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {

                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用：" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
            statsCmd.exec(statisticsResultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_LIMIT, TimeUnit.MILLISECONDS);
                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            System.out.println("这是executeMessage:"+executeMessage);
            executeMessageList.add(executeMessage);
        }

        //删除容器
        StopContainerCmd stopContainerCmd = dockerClient.stopContainerCmd(containerId);
        stopContainerCmd.exec();
        RemoveContainerCmd removeContainerCmd = dockerClient.removeContainerCmd(containerId);
        removeContainerCmd.exec();

        //5、收集整理输出结果
        List<String> outputList=new ArrayList<>();
        long maxTime=0;
        long maxMemory=0;
        for(ExecuteMessage executemessage:executeMessageList){
            Long time = executemessage.getTime();
            Long memory = executemessage.getMemory();
            String message = executemessage.getMessage();
            String errorMessage = executemessage.getErrorMessage();
            if(!StrUtil.isBlank(errorMessage)){
                executeCodeResponce.setMessage(errorMessage);
                //用户提交的代码存在错误，设置状态为3
                executeCodeResponce.setStatus(3);
                break;
            }
            outputList.add(message);
            //程序的执行时间为最大执行时间
            if(time!=null){
                maxTime=Math.max(maxTime,time);
            }
            if(memory!=null){
                maxMemory=Math.max(memory,maxMemory);
            }
        }
        //遍历完所有的executemessage||遇到error的情况退出了
        if(outputList.size()==executeMessageList.size()){
            //正常运行完
            executeCodeResponce.setStatus(1);
        }
        executeCodeResponce.setOutputList(outputList);
        JudgeInfo judgeInfo=new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponce.setJudgeInfo(judgeInfo);

        //5、文件清理
        if(userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除"+(del?"成功":"失败"));
        }

        //6、错误处理，提升程序健壮性——getErrorResponce
        return executeCodeResponce;
    }

    private ExecuteCodeResponce getErrorResponce(Exception e,File userCodeFile){
        if(userCodeFile.getParentFile()!=null){
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除"+(del?"成功":"失败"));
        }
        ExecuteCodeResponce executeCodeResponce=new ExecuteCodeResponce();
        executeCodeResponce.setOutputList(new ArrayList<>());
        executeCodeResponce.setMessage(e.getMessage());
        //2表示代码沙箱错误
        executeCodeResponce.setStatus(1);
        executeCodeResponce.setJudgeInfo(new JudgeInfo());
        return executeCodeResponce;
    }
}
